package com.cyy.springbootinit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.constant.CommonConstant;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.mapper.PaymentBillMapper;
import com.cyy.springbootinit.model.dto.paymentbill.PaymentBillQueryRequest;
import com.cyy.springbootinit.model.entity.PaymentBill;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.PaymentBillVO;
import com.cyy.springbootinit.model.vo.UserVO;
import com.cyy.springbootinit.service.PaymentBillService;
import com.cyy.springbootinit.service.UserService;
import com.cyy.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 缴费单表服务实现
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@Service
@Slf4j
public class PaymentBillServiceImpl extends ServiceImpl<PaymentBillMapper, PaymentBill> implements PaymentBillService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param paymentBill
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validPaymentBill(PaymentBill paymentBill, boolean add) {

        ThrowUtils.throwIf(paymentBill == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        Integer billId = paymentBill.getBillId();
        Date paymentDate = paymentBill.getPaymentDate();
        Double paymentAmount = paymentBill.getPaymentAmount();
        String paymentMethod = paymentBill.getPaymentMethod();
        String paymentPurpose = paymentBill.getPaymentPurpose();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(paymentPurpose), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(paymentAmount==null,ErrorCode.PARAMS_ERROR) ;
           // ThrowUtils.throwIf(paymentMethod==null,ErrorCode.PARAMS_ERROR) ;
        }

        // 修改数据时，有参数则校验
        // todo 补充校验规则
    }

    /**
     * 获取查询条件
     *
     * @param paymentBillQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<PaymentBill> getQueryWrapper(PaymentBillQueryRequest paymentBillQueryRequest) {
        QueryWrapper<PaymentBill> queryWrapper = new QueryWrapper<>();
        if (paymentBillQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Integer paymentId = paymentBillQueryRequest.getPaymentId();
        Long userId = paymentBillQueryRequest.getUserId();
        Integer dormitoryId = paymentBillQueryRequest.getDormitoryId();
        Integer billId = paymentBillQueryRequest.getBillId();
        Date paymentDate =  paymentBillQueryRequest.getPaymentDate();
        Double paymentAmount = paymentBillQueryRequest.getPaymentAmount();
        String paymentMethod = paymentBillQueryRequest.getPaymentMethod();
        String paymentPurpose = paymentBillQueryRequest.getPaymentPurpose();
        String searchText = paymentBillQueryRequest.getSearchText();
        String sortField = paymentBillQueryRequest.getSortField();
        if(sortField==null) sortField="createTime";
        String sortOrder = paymentBillQueryRequest.getSortOrder();
        sortOrder=CommonConstant.SORT_ORDER_DESC;
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(paymentPurpose), "paymentPurpose", paymentPurpose);
        queryWrapper.like(ObjectUtils.isNotEmpty(paymentMethod), "paymentMethod", paymentMethod);
        // JSON 数组查询
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(dormitoryId), "dormitoryId", dormitoryId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(paymentId), "paymentId", paymentId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(paymentAmount), "paymentAmount", paymentAmount);
        queryWrapper.eq(ObjectUtils.isNotEmpty(paymentDate), "paymentDate", paymentDate);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取缴费单表封装
     *
     * @param paymentBill
     * @param request
     * @return
     */
    @Override
    public PaymentBillVO getPaymentBillVO(PaymentBill paymentBill, HttpServletRequest request) {
        // 对象转封装类
        PaymentBillVO paymentBillVO = PaymentBillVO.objToVo(paymentBill);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Long userId = paymentBill.getUserId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "id", userId);
        User user = userService.getOne(queryWrapper);
        paymentBillVO.setUserVO(BeanUtil.copyProperties(user,UserVO.class));
        return paymentBillVO;
    }

    /**
     * 分页获取缴费单表封装
     *
     * @param paymentBillPage
     * @param request
     * @return
     */
    @Override
    public Page<PaymentBillVO> getPaymentBillVOPage(Page<PaymentBill> paymentBillPage, HttpServletRequest request) {
        List<PaymentBill> paymentBillList = paymentBillPage.getRecords();
        Page<PaymentBillVO> paymentBillVOPage = new Page<>(paymentBillPage.getCurrent(), paymentBillPage.getSize(), paymentBillPage.getTotal());
        if (CollUtil.isEmpty(paymentBillList)) {
            return paymentBillVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PaymentBillVO> paymentBillVOList = paymentBillList.stream().map(paymentBill -> {
            return PaymentBillVO.objToVo(paymentBill);
        }).collect(Collectors.toList());


        // 填充信息
        paymentBillVOList.forEach(paymentBillVO -> {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            Long userId = paymentBillVO .getUserId();
            queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "id", userId);
            User user = userService.getOne(queryWrapper);
            paymentBillVO.setUserVO(BeanUtil.copyProperties(user,UserVO.class));
        });
        // endregion
        paymentBillVOPage.setRecords(paymentBillVOList);
        return paymentBillVOPage;
    }

}
